using System;
using UnityEngine;

namespace Shioho.Net
{
    public sealed class ProtoWebsocket : AWebsocket
    {
        public Action OnProtoOpen;
        public Action OnProtoClose;
        public Action OnProtoError;
        public Action OnProtoSilentReconnect;
        public Action<ProtoResponseData> OnProtoResponseMsg;
        public Action<ProtoPushData> OnProtoPushMsg;
        public Action<string> OnProtoRecivedStringMsg;

        public bool IsReconnectWhenServerError = true;
        public int SeqId => _seqId;

        private int _seqId;

        public ProtoWebsocket(string url) : base(url)
        {
        }

        public void ProtoRequest(byte[] buffer)
        {
            SendBinary(buffer);
            _seqId++;
        }

        protected override void OnOpen()
        {
            ResetSeqId();
            OnProtoOpen?.Invoke();
        }

        protected override void OnError()
        {
            OnProtoError?.Invoke();
        }

        protected override void OnSilentReconnect()
        {
            base.OnSilentReconnect();
            OnProtoSilentReconnect?.Invoke();
        }

        protected override void OnClosed()
        {
            OnProtoClose?.Invoke();
        }

        protected override void OnReceivedBinary(byte[] buffer)
        {
            try
            {
                var type = ProtoUtil.GetMsgType(buffer[0]);
                switch (type)
                {
                    case ProtoMsgType.Response:
                        var response = ProtoUtil.DecodeResponseData(buffer);
                        OnProtoResponseMsg?.Invoke(response);
                        break;
                    case ProtoMsgType.Push:
                        var push = ProtoUtil.DecodePushData(buffer);
                        OnProtoPushMsg?.Invoke(push);
                        break;
                    default: break;
                }
            }
            catch (Exception e)
            {
                Debug.LogError(e);
            }
        }

        protected override void OnReceivedString(string message)
        {
            OnProtoRecivedStringMsg?.Invoke(message);
        }

        private void ResetSeqId()
        {
            _seqId = 0;
        }
    }
}
